<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Cover extends Model
{
    use HasFactory;

    protected $guarded = [''];

    public function queryByCategoryName($categoryName, $pageIndex, $pageSize = 5)
    {
        return $this->query()->where('category_name', $categoryName)->where('status', 1)
            ->orderByDesc('created_at')->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
    }

    public function queryByCategoryId($categoryId, $pageIndex, $pageSize = 5)
    {
        return $this->query()->where('category_id', $categoryId)->where('status', 1)
            ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
    }

    public function queryByTags($tags, $pageIndex, $pageSize = 5)
    {
        return $this->query()->where('tags','like',"%$tags%")->where('status', 1)
            ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
    }

    public function queryByOrderName($orderName, $pageIndex, $pageSize = 5)
    {
        return $this->query()->where('status',1)
            ->orderByDesc($orderName)->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
    }

    public function queryByKeyword($keyword, $pageIndex, $pageSize = 5)
    {
        return $this->query()->where('status',1)
            ->where('name','like',"%$keyword%")
            ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
    }

    public function getImagesAttribute($value)
    {
        return explode(',',$value);
    }

    static public function url2path($url)
    {
        $filename = basename($url);
        $hash_hex = md5($filename);
        $hash_hex_l1 = substr($hash_hex, 0, 8);
        $hash_hex_l2 = substr($hash_hex, 8, 8);
        $dir_l1 = hexdec($hash_hex_l1) % 256;
        $dir_l2 = hexdec($hash_hex_l2) % 512;
        $dir = 'uploads/'. $dir_l1. '/' . $dir_l2. '/';

        return $dir . $filename;
    }
}
